﻿using Lgc_VoteSys.Models.BusinessDetails;
using Lgc_VoteSys.Models.Database;
using Lgc_VoteSys.Models.DataUploading;
using Lgc_VoteSys.Service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;

namespace Lgc_VoteSys.Controllers
{
    /// <summary>
    /// 企业详情模块
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BusinessDetailsController : ControllerBase
    {
        // 定义数据库上下文
        private readonly Lgc_VoteSysContext _db;
        private readonly IJWTService _jwtService;

        /// <summary>
        /// 构造方法 构造注入
        /// 把数据库上下文初始化
        /// </summary>
        /// <param name="db"></param>
        public BusinessDetailsController(Lgc_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }

        /// <summary>
        /// 获取企业详情（投票项目详情）信息接口
        /// </summary>
        /// <param name="edId">投票项目Id</param>
        /// <returns></returns>
        [HttpGet]
        public BusinessDetails_GetEnterpriseDetail GetEnterpriseDetail(string edId)
        {
            var enterpriseDetail = _db.EnterpriseDetails.Where(x => x.EdId == edId).ToList();
            if (enterpriseDetail.Count <= 0)
            {
                return null;
            }

            var data = enterpriseDetail.FirstOrDefault();
            BusinessDetails_GetEnterpriseDetail datas = new BusinessDetails_GetEnterpriseDetail();
            datas.ED_id = data.EdId; // 项目id
            datas.Uemail = data.UEmail; // 项目用户邮箱
            datas.PVC_name = data.PvcName; // 项目分类名称
            datas.ED_logo = data.EdLogo; // 项目logo
            datas.ED_name = data.EdName; // 项目名称
            datas.ED_profile = data.EdProfile; // 项目简介
            datas.Award = new DataUploading_award[enterpriseDetail.Count];
            for (int i = 0; i < enterpriseDetail.Count; i++)
            {
                datas.Award[i] = new DataUploading_award();
                datas.Award[i].ED_time = enterpriseDetail[i].EdTime; // 奖项时间
                datas.Award[i].ED_type = enterpriseDetail[i].EdType; // 奖项类型
                int k = 0;
                datas.Award[i].Picture = new DataUploading_picture();
                foreach (var picItem in enterpriseDetail[i].EdPicture.Split(","))
                {
                    if (k == 0)
                    {
                        datas.Award[i].Picture.ED_pic1 = picItem; // 奖项图片
                    }
                    if (k == 1)
                    {
                        datas.Award[i].Picture.ED_pic2 = picItem; // 奖项图片
                    }
                    if (k == 2)
                    {
                        datas.Award[i].Picture.ED_pic3 = picItem; // 奖项图片
                    }
                    if (k == 3)
                    {
                        datas.Award[i].Picture.ED_pic4 = picItem; // 奖项图片
                    }
                    if (k == 4)
                    {
                        datas.Award[i].Picture.ED_pic5 = picItem; // 奖项图片
                    }
                    k++;
                }
            }
            return datas;
        }

        /// <summary>
        /// 投票接口
        /// </summary>
        /// <param name="voteitem">项目编号</param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]//标签 接口需要授权
        public string postVote(BusinessDetails_postVote voteitem)
        {
            // 判断项目是否存在
            var ED_cherck = _db.EnterpriseDetails.Where(x => x.EdId == voteitem.id).ToList();
            if (ED_cherck.Count <= 0)
            {
                return "项目不存在";
            }

            //获取用户信息           登录用户 消息载荷 查询第一条（条件是Type==）   获取登录用户的用户名
            var userEmail = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value; // 获取登录用户的手机号

            // 获取用户的类型 0为普通用户 1为企业用户
            var userType = _db.Users.Where(x => x.UEmail == userEmail).Select(x => x.UType).FirstOrDefault();
            if (userType == 1)
            {
                return "企业用户不能投票";
            }

            // 如果项目未通过审核，不能投票
            if (ED_cherck.FirstOrDefault().EdState != 1)
            {
                return "项目未通过审核，不能投票";
            }

            // 获取当前的日期 2024-05-05
            DateTime date = Convert.ToDateTime(System.DateTime.Now.Year + "-" + System.DateTime.Now.Month + "-" + System.DateTime.Now.Day);

            // 查询投票记录表
            var check = _db.VotingRecords.Where(x => x.VrEmail == userEmail && x.VrDate == date).ToList();
            if (check.Count > 0) // 如果数据库中有当天的投票次数记录
            {
                if(int.Parse(check.FirstOrDefault().VrCount) >= 5) // 如果当天的投票次数超过3次
                {
                    return "今日投票次数已用完";
                }
                check.FirstOrDefault().VrCount = (int.Parse(check.FirstOrDefault().VrCount) + 1).ToString();
            }
            else
            {
                check = _db.VotingRecords.Where(x => x.VrEmail == userEmail).ToList();
                if (check.Count <= 0) // 如果数据库中连用户的投票记录都没有
                {
                    _db.VotingRecords.Add(new VotingRecord
                    {
                        VrEmail = userEmail,
                        VrDate = date,
                        VrCount = "1"
                    });
                }
                else
                {
                    check.FirstOrDefault().VrDate = date;
                    check.FirstOrDefault().VrCount = "1";
                }
            }

            // 进行投票
            var vote = _db.Votes.Where(x => x.EdId == voteitem.id).ToList();
            if(vote.Count <= 0)
            {
                _db.Votes.Add(new Vote
                {
                    EdId = voteitem.id,
                    VCount = "1"
                });
            }
            else
            {
                vote.FirstOrDefault().VCount = (int.Parse(vote.FirstOrDefault().VCount) + 1).ToString();
            }


            var row = _db.SaveChanges();
            if (row > 0)
            {
                return "投票成功";
            }
            else
            {
                return "投票失败";
            }
        }
    }
}
